import { toHex2, toHex4, toHex8 } from "@/utils/hex";

export class Reg {

    name: string;
    bit: number;

    constructor(name: string, bit: number) {
        this.name = name;
        this.bit = bit;
    }

    modify(mask: number, value: number) {
        if (mask == 0x00) {
            return '';
        }

        const v = mask & value;
        if (v == 0x00) {
            return `${this.name} &= ~${this.toHex(mask)};`;
        } else if (v == mask) {
            return `${this.name} |= ${this.toHex(value)};`;
        }
        return `${this.name} = ${this.name} & (~${this.toHex(mask)}) | ${this.toHex(value)};`;
    }

    write1(value: number) {
        if (value == 0x00) {
            return '';
        }
        return this.write(value);
    }

    write(value: number) {
        return `${this.name} = ${this.toHex(value)};`;
    }

    toHex(value: number) {
        if (this.bit == 8) {
            return `0x${toHex2(value)}`;
        } else if (this.bit == 16) {
            return `0x${toHex4(value)}`;
        } else if (this.bit == 32) {
            return `0x${toHex8(value)}`;
        }
        throw 'invalid bit';
    }
}
